# 本文件的功能：
# 遍历当前目录所有c文件和cpp文件，分别用cc和cxx编译
# 递归子目录（排除lib和include、build），编译子目录（将生成a文件到build目录中）
# 将本目录o文件和build里面的子目录库，一起生成可执行程序
export CC := arm-rockchip830-linux-uclibcgnueabihf-gcc
export CXX := arm-rockchip830-linux-uclibcgnueabihf-g++
export AR := arm-rockchip830-linux-uclibcgnueabihf-ar

# 可执行文件名称
APP_NAME := luckfox-to-12dsj

SUBDIRS := $(wildcard */) # 遍历所有子目录
SUBDIRS := $(subst lib/,,$(SUBDIRS)) # 去除lib目录
SUBDIRS := $(subst build/,,$(SUBDIRS)) # 去除build目录
SUBDIRS := $(subst include/,,$(SUBDIRS)) # 去除include目录

SRCS := $(wildcard *.c) # 遍历所有c文件
OBJS := $(SRCS:.c=.o) # 替换文件后缀
SRCS_CPP := $(wildcard *.cpp) # 遍历所有cpp文件
OBJS_CPP := $(SRCS_CPP:.cpp=.o) # 替换文件后缀

CFLAGS := -Wall -Werror -Wshadow -Wno-psabi -g -fpic -rdynamic
CFLAGS += -I./ -I./include -I./drivers/include

LDFLAGS += -lpthread
LDFLAGS += -L./lib -lssl -lcrypto -lzmq -lmosquitto
LDFLAGS += -L./drivers -ldrivers

all: clear build-sub $(OBJS) $(OBJS_CPP)
	$(eval SUBLIB := $(wildcard ./build/*.a)) # 遍历build目录，引入静态库
	$(eval SUBLIB := $(subst ./build/lib,-l,$(SUBLIB:.a=)))
	$(CXX) $(OBJS) $(OBJS_CPP) $(LDFLAGS) -L./build $(SUBLIB) -o $(APP_NAME)
	cp -f $(APP_NAME) ../

build-sub:
	for dir in $(SUBDIRS); do \
		$(MAKE) -C $$dir -j1 all || exit $$?; \
	done

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.cpp
	$(CXX) $(CFLAGS) -c $< -o $@

clean:
	@echo $(SUBDIRS)
	for dir in ${SUBDIRS}; do \
		$(MAKE) -C $$dir clean || exit $$?; \
	done
	rm -f $(OBJS) $(OBJS_CPP) $(APP_NAME)

clear:
	@echo -e "\n\n\n\n\n\n\n\n\n\n-----------------------------------------------------------------\n\n"
	@clear

test:
	@echo $(SUBLIB)
#ranlib ./lib/libmosquitto.a
#ranlib ./drivers/libdrivers.a
# $(info $(PATH))
# $(CXX) -std=c++11 -E - < /dev/null